﻿using AutoMapper;
using BasicData.Domain.Entities;
using Produce.Application.DTO.Input;
using Produce.Application.DTO.Output;
using Produce.Domain.Entities;
using Produce.Infrastructure.Repositories;
using Produce.Result;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace Produce.Application.Services
{
    public class ProductionDateService : IProductionDateService
    {
        private readonly IProduceModelRepository<ProductionDate> _repository;
        private readonly IProduceModelRepository<ProductionPersonSchedule> _personScheduleRepository;
        private readonly IMapper _mapper;
        private readonly ISqlSugarClient _db;
        private readonly ICustomerDataService _customerService;

        public ProductionDateService(
            IProduceModelRepository<ProductionDate> repository,
            IProduceModelRepository<ProductionPersonSchedule> personScheduleRepository,
            IMapper mapper,
            ISqlSugarClient db,
            ICustomerDataService customerService)
        {
            _repository = repository;
            _personScheduleRepository = personScheduleRepository;
            _mapper = mapper;
            _db = db;
            _customerService = customerService;
        }

        /// <summary>
        /// 获取指定人员的排班情况
        /// </summary>
        /// <param name="input">查询条件</param>
        /// <returns>人员排班列表</returns>
        public ApiResult<List<ProductionDateOutput>> GetPersonSchedule(GetPersonScheduleInput input)
        {
            try
            {
                // 计算月份的第一天和最后一天
                var firstDay = new DateTime(input.Year, input.Month, 1);
                var lastDay = firstDay.AddMonths(1).AddDays(-1);

                // 创建结果列表
                var result = new List<ProductionDateOutput>();

                // 如果未提供有效的PersonId，直接返回默认日历数据
                if (input.PersonId <= 0)
                {
                    // 创建整月的默认日历数据
                    for (var date = firstDay; date <= lastDay; date = date.AddDays(1))
                    {
                        result.Add(new ProductionDateOutput
                        {
                            Id = 0,
                            Date = date,
                            Type = (date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday) ? 0 : 1,
                            Remark = "默认排班",
                            CustomerId = 0
                        });
                    }

                    return new ApiResult<List<ProductionDateOutput>>
                    {
                        Success = true,
                        Data = result,
                        Message = "获取默认日历数据成功"
                    };
                }

                // 根据ID查找客户
                CustomerModel customer = _customerService.GetCustomerById(input.PersonId);

                if (customer == null)
                {
                    // 客户不存在时也返回默认日历数据
                    for (var date = firstDay; date <= lastDay; date = date.AddDays(1))
                    {
                        result.Add(new ProductionDateOutput
                        {
                            Id = 0,
                            Date = date,
                            Type = (date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday) ? 0 : 1,
                            Remark = "默认排班",
                            CustomerId = 0
                        });
                    }

                    return new ApiResult<List<ProductionDateOutput>>
                    {
                        Success = true,
                        Data = result,
                        Message = $"未找到ID为 {input.PersonId} 的人员信息，返回默认日历数据"
                    };
                }

                // 查询人员排班数据
                var scheduleData = _db.Queryable<ProductionPersonSchedule>()
                    .Where(x => x.PersonId == input.PersonId &&
                           x.Date >= firstDay &&
                           x.Date <= lastDay &&
                           x.IsDeleted == false)
                    .ToList();

                // 创建整月的日历数据
                for (var date = firstDay; date <= lastDay; date = date.AddDays(1))
                {
                    // 查找当前日期是否有记录
                    var existingSchedule = scheduleData.FirstOrDefault(x => x.Date?.Date == date.Date);

                    if (existingSchedule != null)
                    {
                        // 使用现有记录
                        result.Add(new ProductionDateOutput
                        {
                            Id = existingSchedule.Id,
                            Date = existingSchedule.Date ?? date, // 添加空值检查
                            Type = existingSchedule.Type,
                            Remark = existingSchedule.Remark,
                            CustomerId = input.PersonId
                        });
                    }
                    else
                    {
                        // 创建默认记录（工作日默认为上班，周末默认为休息）
                        result.Add(new ProductionDateOutput
                        {
                            Id = 0,
                            Date = date,
                            Type = (date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday) ? 0 : 1,
                            Remark = "默认排班",
                            CustomerId = input.PersonId
                        });
                    }
                }

                return new ApiResult<List<ProductionDateOutput>>
                {
                    Success = true,
                    Data = result,
                    Message = $"获取 {customer.CustomerName} 的排班数据成功"
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<List<ProductionDateOutput>>
                {
                    Success = false,
                    Message = $"获取人员排班数据失败: {ex.Message}"
                };
            }
        }

        /// <summary>
        /// 设置指定人员的排班
        /// </summary>
        /// <param name="input">排班信息</param>
        /// <returns>操作结果</returns>
        public ApiResult<int> SetPersonSchedule(PersonScheduleInput input)
        {
            try
            {
                // 如果未提供PersonId或PersonId无效
                if (input.PersonId <= 0)
                {
                    // 使用默认值创建排班记录
                    var defaultSchedule = new ProductionPersonSchedule
                    {
                        Id = YitIdHelper.NextId(),
                        PersonId = 0,
                        PersonName = "默认排班",
                        Date = input.Date.Date,
                        Type = input.Type,
                        Remark = input.Remark ?? string.Empty,
                        IsDeleted = false,
                        CreatedAt = DateTime.Now,
                        CreatedBy = input.CreatedBy ?? "system",
                        UpdatedAt = DateTime.Now,
                        UpdatedBy = input.CreatedBy ?? "system"
                    };

                    var createResult = _personScheduleRepository.Create(defaultSchedule);
                    return new ApiResult<int>
                    {
                        Success = createResult > 0,
                        Data = createResult,
                        Message = createResult > 0 ? "创建默认排班成功" : "创建默认排班失败"
                    };
                }

                // 根据ID查找客户
                CustomerModel customer = _customerService.GetCustomerById(input.PersonId);

                if (customer == null)
                {
                    // 客户不存在时也创建排班记录，但使用未知人员作为PersonName
                    var unknownPersonSchedule = new ProductionPersonSchedule
                    {
                        Id = YitIdHelper.NextId(),
                        PersonId = input.PersonId,
                        PersonName = "未知人员",
                        Date = input.Date.Date,
                        Type = input.Type,
                        Remark = input.Remark ?? string.Empty,
                        IsDeleted = false,
                        CreatedAt = DateTime.Now,
                        CreatedBy = input.CreatedBy ?? "system",
                        UpdatedAt = DateTime.Now,
                        UpdatedBy = input.CreatedBy ?? "system"
                    };

                    var createResult = _personScheduleRepository.Create(unknownPersonSchedule);
                    return new ApiResult<int>
                    {
                        Success = createResult > 0,
                        Data = createResult,
                        Message = createResult > 0 ? $"创建ID为 {input.PersonId} 的未知人员排班成功" : $"创建未知人员排班失败"
                    };
                }

                // 查找是否已存在记录
                var existingSchedule = _db.Queryable<ProductionPersonSchedule>()
                    .Where(x => x.PersonId == input.PersonId &&
                           x.Date == input.Date.Date &&
                           x.IsDeleted == false)
                    .ToList()
                    .FirstOrDefault();

                if (existingSchedule != null)
                {
                    // 更新现有记录
                    existingSchedule.Type = input.Type;
                    existingSchedule.Remark = input.Remark ?? string.Empty;
                    existingSchedule.UpdatedAt = DateTime.Now;
                    existingSchedule.UpdatedBy = input.CreatedBy ?? "system";

                    var updateResult = _personScheduleRepository.Update(existingSchedule);
                    return new ApiResult<int>
                    {
                        Success = updateResult > 0,
                        Data = updateResult,
                        Message = updateResult > 0 ? $"更新 {customer.CustomerName} 的排班成功" : $"更新 {customer.CustomerName} 的排班失败"
                    };
                }
                else
                {
                    // 创建新记录
                    var newSchedule = new ProductionPersonSchedule
                    {
                        Id = YitIdHelper.NextId(),
                        PersonId = input.PersonId,
                        PersonName = customer.CustomerName ?? "未命名", // 防止空值
                        Date = input.Date.Date,
                        Type = input.Type,
                        Remark = input.Remark ?? string.Empty,
                        IsDeleted = false,
                        CreatedAt = DateTime.Now,
                        CreatedBy = input.CreatedBy ?? "system",
                        UpdatedAt = DateTime.Now,  // 初始创建时，更新时间与创建时间相同
                        UpdatedBy = input.CreatedBy ?? "system"  // 初始创建时，更新人与创建人相同
                    };

                    var createResult = _personScheduleRepository.Create(newSchedule);
                    return new ApiResult<int>
                    {
                        Success = createResult > 0,
                        Data = createResult,
                        Message = createResult > 0 ? $"创建 {customer.CustomerName} 的排班成功" : $"创建 {customer.CustomerName} 的排班失败"
                    };
                }
            }
            catch (Exception ex)
            {
                return new ApiResult<int>
                {
                    Success = false,
                    Data = 0,
                    Message = $"设置人员排班失败: {ex.Message}"
                };
            }
        }
    }
}
